﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;

namespace GiMess
{
    public static class FormsManager
    {
        private static ArrayList formsList;
        private static MainForm  mainForm;

        public static void Init()
        {
            formsList = new ArrayList();
        }

        public static MainForm MainForm
        {
            get { return mainForm; }
            set { mainForm = value; }
        }

        public static void RemoveIMForm(IMForm form)
        {
            formsList.Remove(form);
        }

        public static void HandleIM(string fromUsername, string fullName, string messageText)
        {
            IMForm form = IMFormExists(fromUsername);
            if (form != null)
            {
                form.AddIMText(messageText);
            }
            else
            {
                mainForm.Invoke(new MethodInvoker(delegate()
                {
                    IMForm imForm = new IMForm(fullName, fromUsername);
                    formsList.Add(imForm);
                    imForm.Show();
                    imForm.AddIMText(messageText);
                    imForm.BringToFront();
                }));
            }
        }

        private static void InvokeCreateIMForm(string fullName, string username)
        {
            mainForm.Invoke(new MethodInvoker(delegate() {
                IMForm imForm = new IMForm(fullName, username);
                formsList.Add(imForm);

                imForm.Show();
            }));
        }

        public static IMForm CreateIMForm(string fullName, string username)
        {
            IMForm imForm = new IMForm(fullName, username);
            formsList.Add(imForm);

            imForm.Show();
            return imForm;
        }

        public static void OpenIMForm(string name, string username)
        {
            IMForm form = IMFormExists(username);
            if ( form == null)
            {
                CreateIMForm(name, username);
            }
            else form.BringToFront();
        }

        private static IMForm IMFormExists(string username)
        {
            foreach (IMForm form in formsList)
            {
                if (form.IMUsername == username) return form;
            }
            return null;
        }

    }
}
